import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzCarouselComponent } from 'ng-zorro-antd';
import { map } from 'rxjs/operators';
import { SheetService } from '@services/sheet.service';
import { Banner, HotTag, Singer, SongSheet } from '@services/data-types/common.type';
import { BatchActionsService } from '@store/batch-actions.service';
import { ModalTypes } from '@store/reducers/member.reducer';
import { select, Store } from '@ngrx/store';
import { AppStoreModule } from '@store/index';
import { getMember, getUserId } from '@store/selectors/member.selector';
import { MemberService } from '@services/member.service';
import { User } from '@services/data-types/member.type';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})

export class HomeComponent implements OnInit {
  hotTags: HotTag[];
  songSheet: SongSheet[];
  banners: Banner[];
  singers: Singer[];
  user: User;
  carouselCurrentIndex = 0;
  @ViewChild(NzCarouselComponent, { static: true }) private nzCarousel: NzCarouselComponent;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private sheetService: SheetService,
    private memberService: MemberService,
    private batchActionsService: BatchActionsService
  ) {
    this.route.data.pipe(map(res => res.homeData)).subscribe(([banners, hotTags, songSheet, singers]) => {
      this.banners = banners;
      this.hotTags = hotTags;
      this.songSheet = songSheet;
      this.singers = singers;
    });
  }

  ngOnInit() {
    this.store$.pipe(select(getMember), select(getUserId)).subscribe(id => {
      if (id) {
        this.memberService.getUserDetail(id).subscribe(res => {
          this.user = res;
        });
      } else {
        this.user = null;
      }
    });
  }
  carouselChanged({ to }) {
    this.carouselCurrentIndex = to;
  }
  changeCarousel(type: 'pre'|'next') {
    this.nzCarousel[type]();
  }
  playSongSheet(id: number) {
    this.sheetService.playSongSheet(id).subscribe(list => {
      this.batchActionsService.selectPlayList({ list, index: 0 });
    });
  }
  skipToSheetInfo(id: number): void {
    this.router.navigate(['/sheetInfo', id]).then();
  }
  skipSingerDetail(id: number): void {
    if (this.user) {
      this.router.navigate(['/singer', id]).then();
    } else {
      this.showModal();
    }
  }
  showModal() {
    this.batchActionsService.controlModalVisible(true, ModalTypes.LoginByPhone);
  }
}
